
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 10px;
        }
        #chat {
            height: 600px;
            overflow-y: scroll;
            border: 1px solid #ccc;
            padding: 10px;
        }
        #messageForm {
            margin-top: 10px;
        }
        select {
            padding: 5px;
        }
        input[type="text"] {
            padding: 5px;
        }
        button {
            padding: 5px 10px;
        }
    </style>
</head>
<body>
<div id="chat"></div>
<form id="messageForm">
    <select name="receiver" id="receiverSelect">
        <option value="all">All</option>
        <!-- 这里可以动态添加在线用户选项 -->
    </select>
    <input type="text" name="message" placeholder="Type your message">
    <button type="button" onclick="sendMessage()">Send</button>
</form>
<script type="text/javascript">
    let lastMessageId = 0;
    let receivedMessageIds = new Set(); // 用于存储已接收的消息ID

    function sendMessage() {
        var receiver = document.getElementById('receiverSelect').value;
        var messageInput = document.getElementsByName('message')[0];
        var message = messageInput.value;
        if (message.trim() !== '') {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'ChatServlet', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            var sender = '<%= session.getAttribute("userName") %>'; // 从 session 中获取发送者的用户名
            if (receiver === 'all') {
                xhr.send('sender=' + encodeURIComponent(sender) + '&message=' + encodeURIComponent(message) + '&receiver=all');
            } else {
                xhr.send('sender=' + encodeURIComponent(sender) + '&message=' + encodeURIComponent(message) + '&receiver=' + encodeURIComponent(receiver));
            }
            messageInput.value = '';
        }
    }

    function updateOnlineUsers() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'ChatServlet?action=getOnlineUsers', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var onlineUsers = JSON.parse(xhr.responseText);
                var select = document.getElementById('receiverSelect');
                select.innerHTML = '<option value="all">All</option>';
                onlineUsers.forEach(function (user) {
                    if (user !== '<%= session.getAttribute("userName") %>') {
                        var option = document.createElement('option');
                        option.value = user;
                        option.text = user;
                        select.appendChild(option);
                    }
                });
            }
        };
        xhr.send();
    }

    function receiveMessages() {
        var source = new EventSource('ChatServlet?action=getMessages&lastMessageId=' + lastMessageId);
        source.onmessage = function (event) {
            var messageId = event.lastEventId;
            if (!receivedMessageIds.has(messageId)) {
                receivedMessageIds.add(messageId);
                lastMessageId = messageId;
                var chatDiv = document.getElementById('chat');
                var message = document.createElement('div');
                message.textContent = event.data;
                chatDiv.appendChild(message);
                chatDiv.scrollTop = chatDiv.scrollHeight;
            }
        };

        // 关闭 EventSource 以防止内存泄漏
        window.addEventListener('beforeunload', function () {
            source.close();
        });
    }

    function showWelcomeMessage() {
        var chatDiv = document.getElementById('chat');
        var welcomeMessage = document.createElement('div');
        welcomeMessage.textContent = "欢迎来到聊天室，<%= session.getAttribute("userName") %>!";
        chatDiv.appendChild(welcomeMessage);
        chatDiv.scrollTop = chatDiv.scrollHeight;
    }

    window.onload = function () {
        showWelcomeMessage();
        updateOnlineUsers();
        receiveMessages();
    };
</script>
</body>
</html>